/*************************************************************************
 *
 *  Copyright (C) 2013 Florian Dang <florian.coin@gmail.com>
 *
 *  This file is part of NatusVerse.
 *
 *  NatusVerse is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  NatusVerse is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with NatusVerse.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************/


#include "image/image.h"

#include <iostream>
#include <fstream>

namespace image
{
//#define ASCII

std::vector<float> & Img::GetVect()
{
	return vimg_;
}


float *Img::GetArray()
{
	float *tmp;
	tmp = &vimg_[0];

	return tmp;
}

float &Img::GetPixel(int idx)
{
	return vimg_[idx];
}

t_format &Img::GetFormat()
{
	return format_;
}

int &Img::GetWidth()
{
	return w_;
}

int &Img::GetHeight()
{
	return h_;
}

int Img::GetSize()
{
	int size = ((format_ == PGM) ? (w_ * h_) : (3 * w_ * h_));

	return size;
}

int Img::GetStep()
{
	return ((format_ == PGM) ? 1 : 3);
}

int Img::Save(std::string filename)
{
	int size = w_ * h_;

	if (format_ == PGM)
		filename += ".pgm";
	else if (format_ == PPM)
		filename += ".ppm";
	else
	{
		std::cerr << "!! Wrong file format" << std::endl;

		return -1;
	}

	std::ofstream file(filename.c_str(), std::ios::out | std::ios::trunc);

	if(file)
	{
		if (format_ == PGM)
			file << "P4" << std::endl;
		else if (format_ == PPM)
		{
			#ifdef ASCII
			file << "P6" << std::endl;
			#else
			file << "P3" << std::endl;
			#endif
			size *= 3;
		}
		file << "# Generated by Mininarette w h max" << std::endl;
		file << w_ << "\t" << h_ << "\t" << MAX_INTENSITY << std::endl;
		for (int i = 0; i < size; i ++)
		{
			#ifdef ASCII
			file << (char) ((int) vimg_[i]);
			#else
			file << (int) vimg_[i] << "\t";
			#endif
			if ((i + 1) % 3 == 0)
				file << std::endl;
		}
		file.close();
	}
	else
	{
		std::cerr << "!! Cannot save image" << std::endl;

		return -1;
	}

	return 0;
}

}
